package com.arlen.general.filter;

import com.arlen.general.exceptionHandle.WxCustomException;
import com.arlen.general.util.MessageThread;
import com.arlen.general.util.WxMessageUtil;
import com.sun.net.httpserver.Filter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

@Component
@WebFilter("/*")
public class GetInformationFilter extends GenericFilter implements Ordered {

    @Autowired
    RedisTemplate redisTemplate;

    private static final ThreadLocal<String> t_uuid = new ThreadLocal<>();

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest servletRequest = (HttpServletRequest) request;
        HttpServletResponse servletResponse = (HttpServletResponse) response;
        String method = servletRequest.getMethod();
        if (!"POST".equals(method) || !((HttpServletRequest) request).getRequestURL().toString().contains("cutIn")) {
            chain.doFilter(request, response);
        }
        String uuid = UUID.randomUUID().toString();
        t_uuid.set(uuid);
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(t_uuid.get(), "");
        if (!aBoolean) {
            redisTemplate.delete(t_uuid.get());
            chain.doFilter(request, response);
        }
        Map<String, String[]> map = request.getParameterMap();
        if (null==map){
            throw new WxCustomException("boys is null !");
        }
        Map<String, String> messMap = WxMessageUtil.analysisMessage(servletRequest);
        MessageThread.setMessageThread(messMap);
        chain.doFilter(request, response);
    }

    @Override
    public int getOrder() {
        return 10;
    }
}
